package com.speechb.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.speechb.controller.base.BaseController;
import com.speechb.entity.KeyValue;
import com.speechb.mapper.KeyValueMapper;
import com.speechb.modules.system.web.annotation.CheckParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2020/8/18 13:05
 */
@RestController
@RequestMapping("${adminRoot}/config")
public class ConfigAdminController extends BaseController {
    @Autowired
    KeyValueMapper keyValueMapper;

    @GetMapping("")
    @ResponseBody
    public void index() {
        Integer pageNum = getPageNum();
        Integer pageSize = Integer.parseInt(getPara("page_size","0"));
        String order = getPara("order");
        String search = getPara("search");
        if (StringUtils.isNotEmpty(search)) {
            search = "%"+search+"%";
        }
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize, true);
        List<KeyValue> listOfAdmin = keyValueMapper.findListOfAdmin(order,search);
        writeData(listOfAdmin,(int)objects.getTotal());
    }

    @PostMapping("/update")
    @CheckParam(value = {"pk","value", "name=[\\d_a-zA-Z]+"},pattern = true)
    public void updateKey() {
        int id = getInt("pk");
        String name = getPara("name");
        String value = getPara("value");
        String updateKeyName = name.replaceFirst(String.valueOf(id), "");
        int updateSize = keyValueMapper.update(id, updateKeyName, value);
        if (updateSize >= 1) {
            renderUnCompressSuccess();
        } else {
            renderFail();
        }
    }

    @PostMapping("/publish")
    @CheckParam(value = {"key","value"},pattern = true)
    public void publish() {
        String key = getPara("key");
        String value = getPara("value");
        String desc = getPara("desc");
        keyValueMapper.insertKeyValue(key, value, desc);
        renderUnCompressSuccess();
    }
}
